#include "OrthographicCameraController.h"
#include "hzpch.h"

#include "Hazel/src/Hazel/Input.h"
#include "Hazel/src/Hazel/KeyCodes.h"
namespace Hazel
{
OrthographicCameraController::OrthographicCameraController(float aspactRatio, bool rotation)
    : m_AspactRatio(aspactRatio),
      m_Bounds(-m_AspactRatio * m_ZoomLevel, m_AspactRatio * m_ZoomLevel, -m_ZoomLevel, m_ZoomLevel),
      m_Camera(m_Bounds.Left, m_Bounds.Right, m_Bounds.Bottom, m_Bounds.Top), m_Rotation(rotation)
{
}

void OrthographicCameraController::OnUpdate(Timestep ts)
{
    HZ_PROFILE_FUNC();

    if (Input::IsKeyPressed(HZ_KEY_A))
        m_CameraPosition.x -= m_CameraTranslateSpeed * ts;
    else if (Input::IsKeyPressed(HZ_KEY_D))
        m_CameraPosition.x += m_CameraTranslateSpeed * ts;

    if (Input::IsKeyPressed(HZ_KEY_S))
        m_CameraPosition.y -= m_CameraTranslateSpeed * ts;
    else if (Input::IsKeyPressed(HZ_KEY_W))
        m_CameraPosition.y += m_CameraTranslateSpeed * ts;
    if (m_Rotation)
    {
        if (Input::IsKeyPressed(HZ_KEY_Q))
            m_CameraRotation += m_CameraRotationSpeed * ts;
        else if (Input::IsKeyPressed(HZ_KEY_E))
            m_CameraRotation -= m_CameraRotationSpeed * ts;
        m_Camera.SetRotation(m_CameraRotation);
    }
    m_Camera.SetPosition(m_CameraPosition);
    m_CameraTranslateSpeed = m_ZoomLevel;
}
void OrthographicCameraController::OnEvent(Event &e)
{
    HZ_PROFILE_FUNC();

    EventDispatcher dispatcher(e);
    dispatcher.Dispatch<MouseScrolledEvent>(HZ_BIND_EVENT_FN(OrthographicCameraController::OnMouseScrolled));
    dispatcher.Dispatch<WindowResizeEvent>(HZ_BIND_EVENT_FN(OrthographicCameraController::OnWindowResized));
}
void OrthographicCameraController::OnResize(float width, float height)
{
    m_AspactRatio = width / height;
    RecalculateView();
}
void OrthographicCameraController::RecalculateView()
{
    m_Bounds = {-m_AspactRatio * m_ZoomLevel, m_AspactRatio * m_ZoomLevel, -m_ZoomLevel, m_ZoomLevel};
    m_Camera.SetProjection(m_Bounds.Left, m_Bounds.Right, m_Bounds.Bottom, m_Bounds.Top);
}
bool OrthographicCameraController::OnMouseScrolled(MouseScrolledEvent &e)
{
    HZ_PROFILE_FUNC();

    m_ZoomLevel -= e.GetYOffset() * 0.25f;
    m_ZoomLevel = m_ZoomLevel < 0.25f ? 0.25 : m_ZoomLevel;

    RecalculateView();
    return false;
}
bool OrthographicCameraController::OnWindowResized(WindowResizeEvent &e)
{
    HZ_PROFILE_FUNC();

    OnResize(e.GetWidth(), e.GetHeight());
    // RecalculateView();
    return false;
}
} // namespace Hazel